<!-- 健教指导管理页面  zxy-2022-12-26 -->
<script setup lang='ts' name="HealthGuide">
import { onBeforeMount, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox, FormRules } from 'element-plus'

import { ColorTheme, ColorRed, DialogType } from '@/api/config'
import {
  getHealthGuideList, deleteHealthGuide, getHealthScanList,
  HealthGuideInfor, TableOperation, HealthGuideFormInfor, SearchHealthGuideFromData, HealthGuideScanInfor
} from '@/api/physicalExaminationManager/healthGuide'
import { transfDicArrData, getObjectByKey } from '@/util/common'

import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {OperButton, SearchButton, SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import dTable from '@/components/dTable/dTable.vue'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'

import addHealthGuide from './addHealthGuide.vue'
import manageHealthGuide from './manageHealthGuide.vue'

import useStore from '@/store/common'
const {store} = useStore.setup()

//显示加载状态
const showLoading = ref(false)

//当前页面 表格数据 定义
const tableData = ref<Array<HealthGuideInfor & RowOperbuttons>>([])
//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop:'name', label:'健教名称', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'bigTypeName', label:'健教大类', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'smallTypeName', label:'健教小类', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'businessTypeName', label:'业务类型', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'icdCodes', label:'ICD-10疾病编码', columnType:'text', align:'left', 'min-width':'100'},
  {prop:'oper', label:'操作', columnType:'slot', align:'left', 'width':'110', fixed:'right'}
])

//健教内容表格数据
const contentTableData = ref<Array<HealthGuideScanInfor>>([])
//健教内容表格头部数据
const contentTableHeaderData = ref<Array<HeaderData>>([
  {prop:'healthValue', label:'健康内容', columnType:'text', align:'left', 'min-width':'100'}

])
//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {label:'健教大类', placeholder:'请选择健教大类', prop:'bigType', type:'selete', changeSubmit:true, seleteData:[]},
  {label:'业务类型', placeholder:'请选择业务类型', prop:'businessType', type:'selete', changeSubmit:true, seleteData:[]},
  {label:'健教名称', placeholder:'请输入健教名称', prop:'name', type:'input', enterSubmit:true}
])

const searchFromRules = reactive<FormRules>({
  name:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ],
  bigTypeName:[
    {required:false, message:'长度应不超过50个字符', max:50, trigger: ['change', 'blur']}
  ]
})

const searchFromData = reactive<SearchHealthGuideFromData>({name:null, bigType:null, businessType:null})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {label:'新增', type:'noraml', iconConfig:{icon:'common-add', type:'custom'}, code:'add'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage:defaultPage,
  pageSize:defaultPageSize,
  pageSizes:defaultPageSizes,
  total:0,
  disabled:false,
  layout:defaultLayout
})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type:'search'},
  {type:'clear'}
])

//操作按钮定义
const rowOperButtons:Array<Oper> = [
  {code:'edit', label:'编辑', iconConfig:{icon:'common-edit', type:'custom', color:ColorTheme, size:20}},
  {code: 'manage', label: '配置', iconConfig: {icon: 'common-maintain', type: 'custom', color:ColorTheme, size: 20}},
  {code:'delete', label:'删除', iconConfig:{icon:'common-delete', type:'custom', color:ColorRed, size:20}}
]

//默认选中的行
const defaultSeleted = ref<HealthGuideInfor&RowOperbuttons>()

//后端数据拼接字段事件
const setTableData = (data:Array<HealthGuideInfor>) => {
  const dataArr:Array<HealthGuideInfor&RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, oper:rowOperButtons})
  })
  tableData.value = dataArr
  defaultSeleted.value = tableData.value[0]
}

//搜索数据事件
const searchData = (resetPage?:boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  tableData.value = []
  contentTableData.value = []
  getHealthGuideList({...searchFromData, page:pageConfig.value.currentPage, limit:pageConfig.value.pageSize}).then((res) => {
    showLoading.value = false
    const {data} = res.data
    pageConfig.value.total = data.total === null ? 0 : data.total
    setTableData(data.records)
  }).catch((error) => {
    showLoading.value = false
    console.warn(error)
  })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
  searchData(true)
}
//获取当前选中行的健康内容
const getHealthScanListData = (id) => {
  getHealthScanList(id).then(res => {
    const {data} = res.data
    contentTableData.value = data
  })
}
//当前选中行的id
const currRowId = ref<string>('')
//获取当前选中行的健康内容
const onRowClick = (row) => {
  if (row && row.id) {
    currRowId.value = row.id
    getHealthScanListData(currRowId.value)
  }
}

//显示弹窗
const showDialog = ref(false)
const showManageDialog = ref(false)

//关闭窗口事件
const onClose = () => {
  showDialog.value = false
  searchData()
}
const onManageClose = () => {
  showManageDialog.value = false
  getHealthScanListData(currRowId.value)
  // searchData()
}

//弹窗类型
const dialogType = ref<DialogType>('add')

//基础健教指导数据模板
const baseHealthGuideFromInfor = {name:'', icdCodeList:[], businessType:undefined, businessTypeName:'', bigType:undefined, bigTypeName:'', smallType:undefined, smallTypeName:'', id:undefined}

//编辑的健教指导数据
const currHealthGuideFromData = ref<HealthGuideFormInfor>({...baseHealthGuideFromInfor})

//清除数据
const clearDialogData = () => {
  currHealthGuideFromData.value = {...baseHealthGuideFromInfor}
}

//操作按钮事件
const onOperation = (name:TableOperation) => {
  if (name === 'add') {
    clearDialogData()
    dialogType.value = 'add'
    showDialog.value = true
  }
}


//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//编辑健教指导信息
const editHealthGuideInfor = (row:HealthGuideFormInfor) => {
  currHealthGuideFromData.value = {...row}
  dialogType.value = 'edit'
  showDialog.value = true
}

//管理健教指导内容
const manageHealthGuideInfor = (row:HealthGuideFormInfor) => {
  currHealthGuideFromData.value = {...row}
  showManageDialog.value = true
}

//健教指导删除
const deleteHealthGuideInfor = (row:HealthGuideInfor) => {
  ElMessageBox.confirm(
    '是否确认删除此健教指导？',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      return deleteHealthGuide(row.id + '')
    }).then(() => {
      ElMessage.success('删除成功')
      searchData(true)
    }).catch((error) => {
      console.warn(error)
    })
}


//操作插槽事件（编辑，删除）事件
const cellOperation = (name:string, row:HealthGuideInfor) => {
  if (name === 'edit') {
    editHealthGuideInfor(row)
  } else if (name === 'manage') {
    manageHealthGuideInfor(row)
  } else if (name === 'delete') {
    deleteHealthGuideInfor(row)
  }
}

//获取字典
const getDic = () => {
  store.getDicData('business_type').then((res) => {
    const item = getObjectByKey(searchFromItems.value, 'prop', 'businessType')
    if (item && item.type === 'selete') {
      item.seleteData = transfDicArrData(res)
    }
  })
  store.getDicData('health_rule_big_type').then((res) => {
    const item = getObjectByKey(searchFromItems.value, 'prop', 'bigType')
    if (item && item.type === 'selete') {
      item.seleteData = transfDicArrData(res)
    }
  })
}




//DOM即将挂载
onBeforeMount(() => {
  getDic()
  searchData()
})
</script>

<template>
  <page-container>
    <div class="wrapper">
      <div class="left">
        <d-table-promote
          :default-seleted="defaultSeleted"
          :label-width="70"
          :show-loading="showLoading"
          :oper-buttons="operButtons"
          :table-data="tableData"
          :table-header-data="tableHeaderData"
          :page-config="pageConfig"
          :search-form-data="searchFromData"
          :search-rules="searchFromRules"
          :search-form-items="searchFromItems"
          :search-from-justify="searchFromJustify"
          :search-buttons="searchButtons"
          @form-submit="onSubmit"
          @form-clear="onFormClear"
          @operation="onOperation"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          @row-click="onRowClick"
        >
          <template #oper="scope">
            <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
          </template>
        </d-table-promote>
      </div>
      <div class="right">
        <d-table
          class="d-common-flex-full"
          :table-data="contentTableData"
          :show-index="true"
          :table-header-data="contentTableHeaderData"
        />
      </div>
    </div>
  </page-container>
  <addHealthGuide v-if="showDialog" :show-dialog="showDialog" :dialog-type="dialogType" :health-guide-data="currHealthGuideFromData" @close="onClose" />
  <manageHealthGuide v-if="showManageDialog" :show-dialog="showManageDialog" :health-guide-data="currHealthGuideFromData" @close="onManageClose" />
</template>

<style scoped>
.wrapper{
  height: 100%;
  display: flex;
  justify-content: space-between;
}
.left{
  width: 60%;
}
.right{
  margin-left: 2%;
  width: 38%;
  border-left:6px solid #F2F2F2;
  padding-left: 2%;
}
</style>